package flextv.display.logic {

import flextv.core.download.WatchId2FlvUrlConverter;
import flextv.core.logic.Logger;
import flextv.core.logic.ResponderAdapter;
import flextv.core.vo.IPlayable;
import flextv.display.view.DisplayPortlet;

import mx.binding.utils.BindingUtils;
import mx.logging.ILogger;
	

public class DisplayPortletController {
	
	private static const LOG: ILogger = Logger.getLog(DisplayPortletController);
	
	private var _portlet: DisplayPortlet;
	
	public function DisplayPortletController(portlet: DisplayPortlet) {
		_portlet = portlet;
		
		BindingUtils.bindSetter(onSetPlayItem, DisplayModel.instance, "playItem");
	}

	
	private function onSetPlayItem(value: Object): void {
		LOG.debug("onSetPlayItem(value="+value+")");
		
		if(value == null) {
			_portlet.videoDisplay.source = null;
			
		} else {
			const item: IPlayable = value as IPlayable;
			
			if(_portlet.videoDisplay.playing) {
				_portlet.videoDisplay.pause();
			}
			
			if(item.fileUri != null) {
				this.playVideoSource(item.fileUri);
			} else { // item is SearchItem
				LOG.debug("Fetching flv url for item.");
				
				new WatchId2FlvUrlConverter(item, new ResponderAdapter(
					function(result: Object): void {
						playVideoSource((result as IPlayable).fileUri);
					},
					function(faultInfo: Object): void {
						throw new Error(faultInfo.toString());
					}
				)).convert();
			}
		}
	}
	
			
	private function playVideoSource(source: String): void {
		LOG.info("playVideoSource(source=" + source + ")");
		_portlet.videoDisplay.source = source; //"file:///Users/phudy/FlexTV_Docs/dummy_file.flv";
		_portlet.videoDisplay.load();
		_portlet.videoDisplay.play();
	}

}
}